<template>
	<div id="app">
		<div class="todo-container">
			<div class="todo-wrap">
				<AddJob :addJob="addJob"></AddJob>
				<!-- 把job列表传给JobList -->
				<JobList :jobs="jobs" :toDelJob="toDelJob" ></JobList>
				<JobProcess :totalJobNum='totalJobNum' :finishJobNum='finishJobNum' :clearFinished='clearFinished' :changeAllState='changeAllState'></JobProcess>
			</div>
		</div>
	</div>
</template>

<script>
	import JobList from './components/JobList.vue'
	import AddJob from './components/AddJob.vue'
	import JobProcess from './components/JobProcess.vue'

	const vm = {
		name: 'App',
		data() {
			return {
				// 任务列表,初始时为空
				jobs: [

				]
			}
		},
		watch:{
			jobs: {
				deep: true,
				handler(newVal) {
					localStorage.setItem("jobs",JSON.stringify(newVal))
				}
			}
		},
		computed: {
			totalJobNum: {
				get() {
					return this.jobs.length
				}
			},
			finishJobNum: {
				get() {
					return this.jobs.reduce((count,job) => count+ (job.finish?1:0),0)
				}
			}
		},
		components: {
			AddJob,
			JobProcess,
			JobList
		},
		methods: {
			// App定义 addJob方法，再把此方法通过props给AddJob组件
			addJob(job) {
				this.jobs.unshift(job)
			},
			toDelJob(id) {
				this.jobs = this.jobs.filter(job => {
					return job.id !== id
				});
			},
			// 全选或全不选
			changeAllState(isTick){
				for(const job of this.jobs) {
					job.finish = isTick
				}
			},
			clearFinished(){
				this.jobs = this.jobs.filter(job => {
					return !job.finish
				});
			}
		},
		// 容器挂载后，加载 localStorage  数据
		mounted(){
			let jobsStr = localStorage.getItem("jobs")
			if(jobsStr!=null)
				this.jobs = JSON.parse(jobsStr)
		}
	}

	export default vm
</script>

<style>
	/*base*/
	body {
		background: #fff;
	}

	.btn {
		display: inline-block;
		padding: 4px 12px;
		margin-bottom: 0;
		font-size: 14px;
		line-height: 20px;
		text-align: center;
		vertical-align: middle;
		cursor: pointer;
		box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
		border-radius: 4px;
	}

	.btn-danger {
		color: #fff;
		background-color: #da4f49;
		border: 1px solid #bd362f;
	}

	.btn-danger:hover {
		color: #fff;
		background-color: #bd362f;
	}

	.btn:focus {
		outline: none;
	}

	.todo-container {
		width: 600px;
		margin: 0 auto;
	}

	.todo-container .todo-wrap {
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 5px;
	}
</style>